﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace JoePack
{
    public class Catalog
    {
        public Catalog()
        {}

        private void Init()
        {
            foreach (Package package in this.Packages)
            {
                foreach (File file in package.Files)
                {
                    file.Package = package;
                }
            }

            foreach (Package package in this.Packages)
            {
                List<Package> dependentpackages = new List<Package>();
                foreach (Package depenetPackage in package.DependentPackages)
                {
                    Package p = findPackage(depenetPackage.Name);
                    if (p!=null) dependentpackages.Add(p);
                }
                package.DependentPackages = dependentpackages;
            }
        }

        private Package findPackage(string name)
        {

            var query = from p in this.Packages
                        where p.Name == name
                        select p;

            return query.FirstOrDefault();
        }

        public string Name { get; set; }

        public List<JoePack.Package> Packages{ get; set; }

        public static Catalog Parse(string path)
        {
            var serializer = new XmlSerializer(typeof (Catalog));
            FileStream fileStream = System.IO.File.OpenRead(path);
            try
            {
                var catalog = (Catalog)serializer.Deserialize(fileStream);
                catalog.Init();
                return catalog;
            }
            finally
            {
                fileStream.Close();    
            }
        }

       

        public void Save(string path)
        {
            var serializer = new XmlSerializer(typeof(Catalog));
            FileStream fileStream = System.IO.File.Create(path);
            try
            {
                serializer.Serialize(fileStream, this);
            }
            finally
            {
                fileStream.Close();    
            }
        }
    }
}
